package the.world.controller;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import the.world.bean.User;
import the.world.service.ListService;
import the.world.service.impl.UserServiceImpl;
import the.world.util.Result;

import javax.servlet.http.HttpSession;


@RestController
public class UserController {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private ListService listService;
    @GetMapping("/zelda/login")
    public ModelAndView loginObject(String username, String password, HttpSession session) {
        User user = userService.selectByUser(username, password);
        ModelAndView modelAndView = new ModelAndView();
        Result<User> result = null;
        if (user != null){
            result = Result.ok(new User[]{user},"登录成功");
            session.setAttribute("user", user);
            modelAndView.setViewName("redirect:/comment/select");
            return modelAndView;
        }
        result = Result.error("登录失败");
        modelAndView.addObject("data", result);
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @PostMapping("/zelda/register")
    public ModelAndView register(String username,String password){
        User user = userService.selectByUser(username, password);
        ModelAndView modelAndView = new ModelAndView();
        if (user != null){
            modelAndView.addObject("error","账号已经存在");
            modelAndView.setViewName("register");
        }else {
            int flag = userService.insert(username,password);
            if (flag > 0){
                modelAndView.setViewName("login");
            }else {
                modelAndView.addObject("error","注册失败");
                modelAndView.setViewName("register");
            }
        }
        return modelAndView;
    }
}
